package com.lagou.client;

import com.lagou.server.service.dto.*;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * RPC消费者类
 * @author yzh
 */
public class RpcConsumer {

    /**
     * 连接池对象
     */
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    /**
     * 用户客户端处理对象
     */
    private static UserClientHandler userClientHandler;

    /**
     * 创建代理对象的方法
     * @param serviceClass
     * @return
     */
    public Object createProxy(final Class<?> serviceClass, final String hostname, final int port){
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                initClient(hostname, port);
                String requestID = UUID.randomUUID().toString().replaceAll("-", "");
                RpcRequest rpcRequest = new RpcRequest(requestID, serviceClass.getName(), method.getName(), method.getParameterTypes(), args);
                userClientHandler.setPara(rpcRequest);
                return executor.submit(userClientHandler).get();
            }
        });
    }

    /**
     * 初始化客户端的方法
     * @throws InterruptedException
     * @param hostname
     * @param port
     */
    public static void initClient(String hostname, int port) throws InterruptedException {
        userClientHandler = new UserClientHandler();
        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap
            .group(group)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.TCP_NODELAY,true)
            .handler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                    pipeline.addLast(new RpcDecoder(RpcResponse.class, new JSONSerializer()));
                    pipeline.addLast(userClientHandler);
                }
            });
        bootstrap.connect(hostname, port).sync();
    }

    public static UserClientHandler getUserClientHandler() {
        return userClientHandler;
    }

}
